import { useState, useEffect } from 'react';
import { DatePicker } from 'antd';
import moment from 'moment';
import { useMemo } from 'react';

const { RangePicker } = DatePicker;

export default ({ fieldName = 'unsafe', limitDays = 30, updateKey, defaultValue, handleChange }) => {

  const className = useMemo(()=>{
    return fieldName + String(Math.random()).split('.')[1]
  }, [])

  useEffect(()=>{
    setValue(defaultValue);
  }, [updateKey])

  //时间的范围选择
  const [dates, setDates] = useState(null);
  const [value, setValue] = useState(defaultValue || [null, null])

  const disabledDate = (current) => {
    if (!dates) {
      return false;
    }
    const tooLate = dates[0] && current.diff(dates[0], 'days') >= limitDays;
    const tooEarly = (dates[1] && dates[1].diff(current, 'days') >= limitDays) || (current && current > moment().endOf('day'));
    return !!tooEarly || !!tooLate;
  };

  const onOpenChange = (open) => {
    setTimeout(()=>{
      if (open) {
        setDates([null, null]);
      } else {
        setDates(null);
      }
    })
  };

  const dateOnFocusHandle = () => {
    try{
      const wrapper = document.getElementsByClassName(className)[0],
      input1 = wrapper.childNodes[0].childNodes[0],
      input2 = wrapper.childNodes[2].childNodes[0],
      value1 = input1.getAttribute('value'),
      value2 = input2.getAttribute('value');
      setDates([(value1 ? moment(value1) : null), (value2 && moment(value2)) || null]);
    }catch(err){
      console.log(err)
    }
  }

  const onChange = (e) => {
    setValue(e);
    handleChange(e);
  }

  return <RangePicker
    className={className}
    showTime={{
      hideDisabledOptions: true,
      defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
    }}
    value={dates || value}
    style={{ width: 380 }}
    onFocus={dateOnFocusHandle}
    disabledDate={disabledDate}
    onCalendarChange={(e)=>setDates(e)}
    onOpenChange={onOpenChange}
    allowClear={false}
    onChange={onChange}
  />
}
